package com.kangdi.riggie.controller;

import com.kangdi.riggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${upload.filePath}")
    private String basePath;
    @PostMapping("upload")
    public Result<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString() + substring;
        String s1 = s.replaceAll("-", "");
        String fileName=basePath+s1;
        try {
            File file1 = new File(basePath);
//            String fileName=basePath+file.getOriginalFilename();
            if (!file1.exists()){
                file1.mkdirs();
            }
            file.transferTo(new File(fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(s1);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        String filename=basePath+name;
        try {
            FileInputStream fileInputStream = new FileInputStream(filename);
            byte[]bytes=new byte[1024];
            int len=0;
            ServletOutputStream outputStream = response.getOutputStream();
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
